package jwt.lab02;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class SendMailWithAttachment {

	public static void main(String[] args) throws MessagingException {
		Properties props = Utils.loadProperties(Utils.PROPERTIES_FILE);
		Session session = Session.getInstance(props, null);

		System.out.println("Sending message with attachment " + props.getProperty("mail.attachment"));

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(props.getProperty("mail.smtp.from")));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("mail.to")));
		message.setSubject("Hello JavaMail Attachment");

		Multipart multipart = new MimeMultipart();

		BodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText("Here's the file");
		multipart.addBodyPart(messageBodyPart);

		messageBodyPart = new MimeBodyPart();
		DataSource source = new FileDataSource(props.getProperty("mail.attachment"));
		messageBodyPart.setDataHandler(new DataHandler(source));
		messageBodyPart.setFileName(props.getProperty("mail.attachment.name"));
		multipart.addBodyPart(messageBodyPart);

		message.setContent(multipart);

		Transport transport = session.getTransport();
		transport.connect(props.getProperty("mail.smtp.user"), props.getProperty("mail.smtp.password"));
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();

		System.out.println("[ OK ]");
	}

}
